<template>
    <div class="memo-container">
        
        <editor v-if="editMode" v-model:content="content"/>
        <div v-else v-html="content" ref="viewBoxRef" class="content beautify-scrollbar" @click="handleClickPreviewBox"></div>


        <!-- 悬浮编辑按钮 -->
        <div
            class="floating-btn"
            :style="{ left: `${editBtn.left}%`, top: `${editBtn.top}%` }"
            @mousedown="onMouseDown"
        >
            <!-- 使用阿里巴巴图标注意：class中前面的iconfont为项目中assets目录下放置图标文件的路径 -->
            <i class="edit iconfont icon-edit" v-if="!editMode"></i>
            <i class="save iconfont icon-baocun1" v-else></i>
        </div>

        <!-- 图片预览框 -->
        <el-image-viewer
            v-if="showImageViewer"
            :url-list="urlList"
            :initial-index="initialIndex"
            :infinite="false"
            @close="closeImageViewer"
        />
    </div>

</template>

<script setup>
import { ref,onMounted,onBeforeUnmount, nextTick } from 'vue';
import { $msg_e,$msg_s } from '../utils/msg.js'
import { $get,$post } from '../utils/request.js'
import { MemoApi, TodoApi } from '@/api/path.js';
import Editor from './Editor.vue';
import { UserState } from '@/store/loginUser.js';

// 备忘录数据
const content = ref('')
// 编辑模式
const editMode = ref(false)
// 查看框ref
const viewBoxRef = ref()


// 获取备忘录
const getUserMemo = async () => {
    const res = await $get(MemoApi.getUserMemo)
    // console.log('getUserMemo-res:', res);
    if(!res.success){
        return $msg_e(res.message)
    }
    const data = res.data
    if(data) content.value = data.content
}

// 保存备忘录数据
const save = async () => {
    // 这个新增接口有更新逻辑
    const res = await $post(MemoApi.add, {content: content.value})
    console.log('saveMemo-res:', res);
    if(!res.success){
        return $msg_e(res.message)
    }
    getUserMemo()
    editMode.value = false
}




// 编辑按钮数据
const editBtn = ref({
    left: 95, // 初始化右侧位置为 100%
    top: 10 // 初始化顶部位置为 0%
})
let isDragging = false // 是否正在拖动
let offsetX = 0 // 鼠标点击时的X偏移
let offsetY = 0 // 鼠标点击时的Y偏移

// 鼠标按下事件处理函数
const onMouseDown = (event) => {
    isDragging = false; // 初始化为非拖动状态
    offsetX = event.clientX - (window.innerWidth * editBtn.value.left) / 100;
    offsetY = event.clientY - (window.innerHeight * editBtn.value.top) / 100;
    document.addEventListener('mousemove', onMouseMove);
    document.addEventListener('mouseup', onMouseUp);
}

// 鼠标移动事件处理函数
const onMouseMove = (event) => {
    if (!isDragging) {
        const distance = Math.sqrt(
            Math.pow(event.clientX - offsetX, 2) + Math.pow(event.clientY - offsetY, 2)
        );
        if (distance > 5) {  // 如果鼠标移动的距离大于阈值，认为是拖动
            isDragging = true;
        }
    }

    if (isDragging) {
        const newLeft = ((event.clientX - offsetX) / window.innerWidth) * 100;
        const newTop = ((event.clientY - offsetY) / window.innerHeight) * 100;
        editBtn.value.left = Math.max(0, Math.min(newLeft, 100));
        editBtn.value.top = Math.max(0, Math.min(newTop, 100));
    }
}

// 鼠标松开事件处理函数
const onMouseUp = () => {
  if(!isDragging){
    onClick()
  }else{
    isDragging = false;
  }
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseUp);
}

// 进入编辑模式
const onClick = () => {
    if(editMode.value){
        save()
    }else{
        editMode.value = true
    }
}


// 图片预览
const showImageViewer = ref(false)
const urlList = ref([])
const initialIndex = ref(0)
const closeImageViewer = () => {
  urlList.value = []
  initialIndex.value = 0
  showImageViewer.value = false
}



// 点击预览box
const handleClickPreviewBox = event => {
    // console.log('handleClickPreviewBox-event:',event);
    if (event.target && event.target.tagName === 'IMG') {
        handleImageClick(event)
    }

    if (event.target && event.target.tagName === 'INPUT' && event.target.type === 'checkbox') {
        handleCheckboxClick(event)
    }
}

// 处理图片点击事件
const handleImageClick = event => {
    // console.log('handleImageClick-event:',event);
    urlList.value.push(event.target.src)
    showImageViewer.value = true
}

// 处理待办事项复选框点击事件
const handleCheckboxClick = async event => {
    let id = event.target.id
    let type = event.target.classList[0]
    let checked = event.target.checked
    // console.log('todo-item, id: ' + id + ' ,type: ' + type + ' ,checked: ' + checked);
    let params = {id,type,finished: checked ? 1 : 0}
    const res = await $post(TodoApi.edit, params)
    if(!res.success){
        return $msg_e(res.message)
    }
}

// 检查待办列表
let checkTodoTimer
const checkTodo = () => {
    // nextTick不一定是渲染完了的，只是vue自己管理下一个时间片段，所以这里简单粗暴使用setTimeout等待页面dom渲染完成
    checkTodoTimer = setTimeout(async () => {
        
        // 获取class为Type的待办事项checkbox元素
        const type = `todo-item-${UserState.loginUser.id}`
        
        const checkboxs = viewBoxRef.value.querySelectorAll('.'+type)
        // console.log('checkboxs:',checkboxs);
        if(!checkboxs || checkboxs.length === 0) return

        const res = await $get(TodoApi.getByType, {type})
        // console.log('getTodoListByType-res:',res);
        if(!res.success) return $msg_e(res.message)

        let todoList = res.data
        if(!todoList) return

        const obj = todoList.reduce((acc, curr) => {
            acc[curr.id] = curr.finished===1 ? true : false;
            return acc;
        }, {});

        console.log('checkTodo-obj:',JSON.stringify(obj));
        checkboxs.forEach(item => {
            // console.log('item:',item);
            let checked = obj[item.id] ? obj[item.id] : false
            item.checked = checked
        })
    },300)
}


onMounted(() => {
    getUserMemo()
    checkTodo()
})
onBeforeUnmount(() => {
    if(checkTodoTimer) clearTimeout(checkTodoTimer)
})


</script>

<style scoped lang="scss">

.memo-container{
    height: 100%;
    overflow: hidden;
    & > .content{
        height: 100%;/**此处要设置Height为100%，overflow为auto，同时外层container要设置overflow为hidden才能滚动 */
        padding: 5px;
        white-space: pre-wrap; /* 保留空格和换行符 */
        font-family: monospace; /* 使用等宽字体 */
    }
}


/**悬浮编辑按钮样式 */
.floating-btn {
  position: fixed;
  width: 40px;
  height: 40px;
  transform: translate(-100%, 0); /* 使按钮右对齐 */
  border-radius: 50%;
  background-color: #3975C6;
  border: none;
  cursor: pointer;
  display: flex;/**设置居中 */
  justify-content: center;
  align-items: center;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.5); /**添加阴影效果 */
  transition: background-color 0.3s ease;/**添加平滑的过渡效果 */
  & > i{
    color: white;
  }
  & > i.edit{
    font-size: 30px;
  }
  & > i.save{
    font-size: 20px;
  }
}

.floating-btn:hover {
  background-color: #24B3F0;
}
</style>